package com.microservice.common.config;

import com.microservice.common.properties.MailProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * 邮件自动配置类
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "spring.mail", name = "enabled", havingValue = "true", matchIfMissing = false)
public class MailConfig {
    
    private final MailProperties mailProperties;
    
    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        
        mailSender.setHost(mailProperties.getHost());
        mailSender.setPort(mailProperties.getPort());
        mailSender.setUsername(mailProperties.getUsername());
        mailSender.setPassword(mailProperties.getPassword());
        mailSender.setDefaultEncoding(mailProperties.getDefaultEncoding());
        
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", mailProperties.getAuth());
        props.put("mail.smtp.ssl.enable", mailProperties.getSslEnable());
        props.put("mail.smtp.starttls.enable", mailProperties.getStarttlsEnable());
        props.put("mail.smtp.starttls.required", mailProperties.getStarttlsRequired());
        
        // SSL 相关配置
        if (mailProperties.getSslEnable()) {
            props.put("mail.smtp.ssl.trust", mailProperties.getHost());
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.port", mailProperties.getPort());
            props.put("mail.smtp.socketFactory.fallback", "false");
        }
        
        // 超时配置（增加超时时间，避免连接超时）
        props.put("mail.smtp.connectiontimeout", "10000");  // 10秒
        props.put("mail.smtp.timeout", "10000");            // 10秒
        props.put("mail.smtp.writetimeout", "10000");       // 10秒
        
        log.info("邮件服务配置完成: host={}, port={}, from={}", 
                 mailProperties.getHost(), 
                 mailProperties.getPort(), 
                 mailProperties.getFrom());
        
        return mailSender;
    }
}
